package com.wx.rpc.service.core;

import com.wx.rpc.constant.ZKConfig;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @author wx
 * @Description: ZK注册业务
 * @date 2019/3/8 000815:45
 */
public class ZkRegisterService implements IRegisterService {
    private CuratorFramework curatorFramework;
    
    
    public ZkRegisterService() {
        /** 初始化Curator */
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(ZKConfig.ZK_HOST).sessionTimeoutMs(4000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
        curatorFramework.start();
    }

    /**
     * @description: 注册服务
     * @author: wx
     * @date: 2019/3/8 0008
     * @param serviceName 服务名
     * @param serviceAddress 服务地址
     * @return: void
     */

    @Override
    public void register(String serviceName, String serviceAddress) {
        try {
            // 注册相应的服务 --> 不存在则创建
            String serviceUrl = ZKConfig.ZK_REGISTER_PATH + "/" + serviceName;
            if (null == curatorFramework.checkExists().forPath(serviceUrl)) {
                //注册服务名称为持久化节点
                curatorFramework.create().creatingParentsIfNeeded()
                        .withMode(CreateMode.PERSISTENT).forPath(serviceUrl, "0".getBytes());
            }
            // 获取地址的完整路径
            String addressUrl = serviceUrl + "/" + serviceAddress;
            // 注册服务器地址为临时节点
            String rsNode = curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(addressUrl, "0".getBytes());
            System.out.println("服务注册成功, rsNode : " + rsNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
